package com.controller;

import com.beans.UserinfoEntity;
import com.common.entity.R;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

@Transactional(rollbackFor = Exception.class)
@RestController
@RequestMapping("userinfo")
public class UserinfoController {

    @PersistenceContext
    private EntityManager entityManager;

    @GetMapping("queryUserinfoAll")
    public R radioDepotPage(Integer state, Integer page, Integer rows, String sort, String order) {
        //region 组装hql
        StringBuilder sql = new StringBuilder("select * from userinfo where 1 = 1 ");
        StringBuilder countSql = new StringBuilder("select count(id) from userinfo where 1 = 1 ");
        if (state != null) {
            sql.append(" and state = :state ");
            countSql.append(" and state = :state ");
        }
        if (!StringUtils.hasLength(sort)) {
            sql.append(" order by ").append(sort).append(" ");
            if (!StringUtils.hasLength(order)) {
                sql.append(order);
            }
        }
        if (page != null && rows != null) {
            sql.append(" limit :offset , :rows ");
        }
        //endregion 组装hql
        //region 组装查询对象和参数
        Query query = entityManager.createNativeQuery(sql.toString(), UserinfoEntity.class);
        Query queryCount = entityManager.createNativeQuery(countSql.toString());
        if (state != null) {
            query.setParameter("state", state);
            queryCount.setParameter("state", state);
        }
        if (page != null && rows != null) {
            query.setParameter("offset", (page - 1) * rows).setParameter("rows", rows);
        }
        List<UserinfoEntity> resultList = query.getResultList();
        Object count = queryCount.getSingleResult();
        R ok = R.ok();
        ok.put("total", count);
        ok.put("rows", resultList);
        return ok;
    }

}
